import jwt
from django.http import JsonResponse
from django.conf import settings
from datetime import datetime, timedelta
from tools.myjwt import mytoken
SECRET_KEY = "your-secret-key"  # 替换为安全的密钥
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

# 白名单路径（不需要 Token 验证的路径）
WHITELISTED_PATHS = [
    '/user/login/',
    '/user/send/',
    '/user/captcha/',
    '/user/dd/login/',
    '/user/dd/login/callback/',
]


class TokenMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 检查请求路径是否在白名单中
        if request.path in WHITELISTED_PATHS:
            return self.get_response(request)

        # 获取 Token
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({"error": "未提供 Token"}, status=401)

        token = auth_header.split(' ')[1]
        try:
            payload = mytoken.gettoken(token)
            request.user_id = payload['userid']

        except jwt.ExpiredSignatureError:
            return JsonResponse({"error": "Token 已过期"}, status=401)
        except jwt.InvalidTokenError:
            return JsonResponse({"error": "无效的 Token"}, status=401)

        return self.get_response(request)

